package com.papers.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.papers.common.annotation.Log;
import com.papers.common.annotation.RepeatSubmit;
import com.papers.common.core.controller.BaseController;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.core.validate.AddGroup;
import com.papers.common.core.validate.EditGroup;
import com.papers.common.enums.BusinessType;
import com.papers.common.excel.ExcelResult;
import com.papers.common.utils.poi.ExcelUtil;
import com.papers.system.domain.bo.TJuanChapterBo;
import com.papers.system.domain.dto.TJuanChapterDto;
import com.papers.system.domain.dto.TJuanChapterSortDto;
import com.papers.system.domain.vo.*;
import com.papers.system.service.ITJuanChapterService;
import com.papers.system.service.ITJuanCourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 章节
 *
 * @author papers
 * @date 2022-10-08
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/juanChapter")
public class TJuanChapterController extends BaseController {

    private final ITJuanChapterService iTJuanChapterService;

    private final ITJuanCourseService itJuanCourseService;

    /**
     * 查询章节列表
     */
    @SaCheckPermission("system:juanChapter:list")
    @GetMapping("/list")
    public TableDataInfo<TJuanChapterVo> list(TJuanChapterDto dto, PageQuery pageQuery) {
        return iTJuanChapterService.queryPageList(dto, pageQuery);
    }

    /**
     * 导入数据
     */
    @Log(title = "测试单表", businessType = BusinessType.IMPORT)
    @SaCheckPermission("system:juanChapter:import")
    @PostMapping("/importData")
    public R importData(@RequestPart("file") MultipartFile file,String courseId) {
        if (ObjectUtils.isEmpty(courseId)){
            return R.fail("请先选择题库");
        }
        InputStream fis = null;
        try {
            fis = file.getInputStream();
            ExcelResult<TJuanChapterOutVo> result = ExcelUtil.importExcel(fis, TJuanChapterOutVo.class, true);
            List<TJuanChapterOutVo> list = result.getList();
            if (list.size() == 0) {
                return R.fail("请先添加数据");
            }
            //保存
            return iTJuanChapterService.saveBatch(list,courseId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出章节列表
     */
    @SaCheckPermission("system:juanChapter:export")
    @Log(title = "章节", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TJuanChapterBo bo, HttpServletResponse response) {
        if (null == bo.getCourseId()){
            throw new RuntimeException("请选择题库再导出");
        }
        List<TJuanChapterPutVo> list = iTJuanChapterService.OutputList(bo);
        ExcelUtil.exportExcel(list, "章节", TJuanChapterPutVo.class, response);
    }

    /**
     * 获取章节详细信息
     *
     * @param chapterId 主键
     */
    @SaCheckPermission("system:juanChapter:query")
    @GetMapping("/{chapterId}")
    public R<TJuanChapterVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String chapterId) {
        return R.ok(iTJuanChapterService.queryById(chapterId));
    }

    /**
     * 新增章节
     */
    @SaCheckPermission("system:juanChapter:add")
    @Log(title = "章节", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TJuanChapterBo bo) {
        //int i = iTJuanChapterService.ChapterCodeUnique(bo);
        //if (i == 0) {
        //    return R.fail("新增章节失败，章节编号" + bo.getChapterCode() + "已存在");
        //}
        return toAjax(iTJuanChapterService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改章节
     */
    @SaCheckPermission("system:juanChapter:edit")
    @Log(title = "章节", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TJuanChapterBo bo) {
        return toAjax(iTJuanChapterService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除章节
     *
     * @param chapterIds 主键串
     */
    @SaCheckPermission("system:juanChapter:remove")
    @Log(title = "章节", businessType = BusinessType.DELETE)
    @DeleteMapping("/{chapterIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] chapterIds) {
        return iTJuanChapterService.deleteByIds(chapterIds);
    }

    /**
     * 根据courseId查询章节(用于知识点树)
     *
     * @return
     */
    @GetMapping("/getChapterTree/{courseId}")
    public R<List<TJuanLeftTreeVo>> getChapterTree(@PathVariable String courseId) {
        List<TJuanLeftTreeVo> chapterTree = iTJuanChapterService.getChapterTreeList(courseId);
        return R.ok(chapterTree);
    }

    /**
     * 查询章节list(用于章节展示)
     *
     * @return
     */
    @GetMapping("/getChapterList")
    public R<List<TJuanChapterVo>> getChapterList(TJuanChapterBo bo) {
        List<TJuanChapterVo> knowledgeList = iTJuanChapterService.getChapterList(bo);
        return R.ok(knowledgeList);
    }

    /**
     * 查询课程树(用于知识点树)
     *
     * @return
     */
    @GetMapping("/getCourseTree")
    public R<List<TJuanCourseTreeVo>> getCourseTree() {
        List<TJuanCourseTreeVo> courseTree = iTJuanChapterService.getCourseTreeList();
        return R.ok(courseTree);
    }

    /**
     * 拖拽修改顺序()
     *
     * @return
     */
    @RequestMapping("/sort")
    public R<Void> sort(@RequestBody TJuanChapterSortDto dto){
        R<Void> sort = iTJuanChapterService.sort(dto);
        return sort;
    }
}
